package org.wisdom.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wisdom.client.MTClient;
import org.wisdom.entity.Order;
import org.wisdom.mapper.OrderMapper;
import org.wisdom.mapstruct.OrderMapStruct;
import org.wisdom.request.PostOrderRequest;
import org.wisdom.service.OrderService;
import org.wisdom.utils.SnowflakeUtils;
import org.wisdom.utils.UserContext;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    SnowflakeUtils snowflakeUtils;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MTClient mtClient;

    @Override
    public void postOrder(PostOrderRequest postOrderRequest) throws IOException {
        Order order = OrderMapStruct.INSTANCE.postOrderRequestToOrder(postOrderRequest);
        order.setOrderId(snowflakeUtils.nextId());
        order.setPublisherId(UserContext.getUser());
        if (postOrderRequest.getPhotos() != null && !postOrderRequest.getPhotos().isEmpty()) {
            String[] photosUrl = new String[postOrderRequest.getPhotos().size()];
            for (int i = 0; i < postOrderRequest.getPhotos().size(); i++) {
                photosUrl[i] = mtClient.upload(postOrderRequest.getPhotos().get(i));
            }
            order.setPhotosUrl(String.join(",", photosUrl));
        }
        order.setCreatedTime(LocalDateTime.now());
        orderMapper.insertOrder(order);
    }

    @Override
    public Order getOrder(Long id) {
        return orderMapper.selectOrder(id);
    }

    @Override
    public List<Order> getBuyOrder() {
        return orderMapper.selectSelfBuyOrder(UserContext.getUser());
    }

    @Override
    public List<Order> getSellOrder() {
        return orderMapper.selectSelfSellOrder(UserContext.getUser());
    }

    @Override
    public List<Order> getPublicAllOrder() {
        return orderMapper.selectPublicAllOrder();
    }

    @Override
    public List<Order> getPublicBuyOrder() {
        return orderMapper.selectPublicBuyOrder();
    }

    @Override
    public List<Order> getPublicSellOrder() {
        return orderMapper.selectPublicSellOrder();
    }
}
